package main

import(
  "net"
  "log"
  "os"
)

type NetworkServer struct{
  Netting
}


func (this* NetworkServer) initialize() (chan Client){
  log.Stdout("---- Starting server ----")

  l, e := net.Listen("tcp", ":10000")
  if e != nil {
    log.Stderr("Error listening: %s", e.String())
    os.Exit(1)
  }
  log.Stdout("Listener created", l)
  
  /* create a channal to send new clients on */
  clients := make(chan Client, 10)
  go this.listen(l, clients)
  return clients
}

func (this* NetworkServer) listen(l net.Listener, clients chan Client){
  for {
    /* wait for connections */
    c, e := l.Accept()
    if e != nil  {
      log.Stderrf("Error accepting: %s", e.String())
    } else {
      log.Stdout("Accepting connection", c)
      in := make(chan string, 100) /* received messages will be forwarded to this channel */
      out := make(chan string, 100) /* messages sent to this channel will be forwarded to the client */
      go this.receiveLoop(in, c)
      go this.sendLoop(out, c)
      client := new(Client)
      client.in = in
      client.out = out
      clients <- *client
    }
  }
}


